package typesys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import util.Pair;

import ast.DQCSystem;
import ast.Principal;
import ast.Term;

public class TypeChecking {
	
	public static boolean check(DQCSystem sys, HashMap<String, HashSet<Term>> rho) 
			throws FunctionUndefinedException 
	{
		
		ArrayList<Principal> plist = new ArrayList<Principal>();
		for (Pair<String, String> afPair : sys.getAfPairs()) {
			if (!hasElement(plist, afPair.getFst())) {
				plist.add(new Principal(afPair.getFst()));
			}
			if (!hasElement(plist, afPair.getSnd())) {
				plist.add(new Principal(afPair.getSnd()));
			}
		}
		PrincipalHierarchy ph = new PrincipalHierarchy(plist);
		for (Pair<String, String> afPair : sys.getAfPairs()) {
			ph.addActsFor(new Principal(afPair.getFst()), new Principal(afPair.getSnd()));
		}
		
		SystemJudgement sysjdgt = new SystemJudgement(sys, rho, ph);
		
		return sysjdgt.check();	
	}
	
	private static boolean hasElement(ArrayList<Principal> prs, String pr) {
		
		for (Principal p : prs) {
			if (p.getName().equals(pr))
				return true;
		}
		
		return false;
	}

}
